package main

import (
	"google.golang.org/grpc"
	"log"
	"grpcTest/customer"
	"context"
)

const address = "localhost:50051"

func main() {
	conn, err := grpc.Dial(address, grpc.WithInsecure())
	if err != nil {
		log.Fatal("did not connect: %v", err)
	}
	defer conn.Close()

	client := customer.NewCustomerClient(conn)

	cs := &customer.CustomerRequest{
		Id: 101,
		Name: "fang",
		Email: "fangdengfu@gg.com",
		Phone: "15851739989",
		Addresses: []*customer.CustomerRequest_Address{
			&customer.CustomerRequest_Address{
				Street: "和平街",
				City: "淮安",
				State: "江苏",
				Zip: "223001",
				IsShippingAddress: false,
			},
			&customer.CustomerRequest_Address{
				Street: "黄埔街道",
				City: "上海",
				State: "上海",
				Zip: "400000",
				IsShippingAddress: true,
			},
		},
	}

	createCustomer(client, cs)

	cs = &customer.CustomerRequest{
		Id: 102,
		Name: "deng",
		Email: "dengfu@qq.com",
		Phone: "123456",
		Addresses: []*customer.CustomerRequest_Address{
			&customer.CustomerRequest_Address{
				Street: "jingjiang",
				City: "luoshanji",
				State: "us",
				Zip: "100000",
				IsShippingAddress:true,
			},
		},
	}

	createCustomer(client, cs)

	filter := &customer.CustomerFilter{Keyword:""}
	getCustomers(client, filter)

}

func createCustomer(client customer.CustomerClient, customer *customer.CustomerRequest) {
	resp, err := client.CreateCustomer(context.Background(), customer)
	if err != nil {
		log.Fatal("could not create customer: %v", err)
	}
	if resp.Success {
		log.Printf("a new customer has been added with id: %d", resp.Id)
	}
}

func getCustomers(client customer.CustomerClient, filter *customer.CustomerFilter) {
	stream, err := client.GetCustomers(context.Background(), filter)
	if err != nil {
		log.Fatal("error on get customers: %v", err)
	}
	for {
		customer, err := stream.Recv()
		if err != nil {
			break
		}
		if err != nil {
			log.Fatal("%v.GetCustomers(_) = _, %v", client, err)
		}
		log.Printf("Customer: %v", customer)
	}
}